package com.scholarship.common.utils;

import org.apache.commons.io.FileUtils;
import org.springframework.core.io.FileSystemResource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.List;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

/**
 * 文件下载工具类
 * Created by sjk on 2017-04-17.
 * update by zjh on 2021-07-21
 */
@Deprecated
public class FileDownloadUtil {

    //文件上传临时路径
    public static final String PATH = PropertiesUtil.getProperty("upload.path");

    public static ResponseEntity<byte[]> downloadOneFile(String originalFileName, String scoreFile) throws Exception {

        String path = FileUploadUtil.PATH + scoreFile;
        //FileSystemResource file = new FileSystemResource(path);
        File file = new File(path);
        HttpHeaders headers = new HttpHeaders();
        headers.add("Cache-Control", "no-cache, no-store, must-revalidate");

        // 设置下载时的文件名，中文文件名需要进行转码，否则是乱码
        headers.add("Content-Disposition",
                "attachment; filename=" + new String(originalFileName.getBytes("UTF-8"),
                        "iso-8859-1"));
        headers.add("Pragma", "no-cache");
        headers.add("Expires", "0");

//        return ResponseEntity
//                .ok()
//                .headers(headers)
//                .contentLength(file.contentLength())
//                .contentType(MediaType.parseMediaType("application/octet-stream"))
//                .body(file);
//        String fileName = new String(originalFileName.getBytes("UTF-8"), "iso-8859-1");
//        headers.setContentDispositionFormData("attachment", fileName);
//        headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
        return new ResponseEntity<byte[]>(FileUtils.readFileToByteArray(file), headers, HttpStatus.CREATED);
    }

    public static void zipFile(List<File> files, ZipOutputStream outputStream) throws IOException {
        try {
            int size = files.size();
            // 压缩列表中的文件
            for (int i = 0; i < size; i++) {
                File file = (File) files.get(i);
                zipFile(file, outputStream);
            }
        } catch (IOException e) {
            throw e;
        }
    }
    private static void zipFile(File inputFile, ZipOutputStream outputstream) throws IOException {
        try {
            if (inputFile.exists()) {
                if (inputFile.isFile()) {
                    FileInputStream inStream = new FileInputStream(inputFile);
                    BufferedInputStream bInStream = new BufferedInputStream(inStream);
                    ZipEntry entry = new ZipEntry(inputFile.getName());
                    outputstream.putNextEntry(entry);

                    final int MAX_BYTE = 10 * 1024 * 1024; // 最大的流为10M
                    long streamTotal = 0; // 接受流的容量
                    int streamNum = 0; // 流需要分开的数量
                    int leaveByte = 0; // 文件剩下的字符数
                    byte[] inOutbyte; // byte数组接受文件的数据

                    streamTotal = bInStream.available(); // 通过available方法取得流的最大字符数
                    streamNum = (int) Math.floor(streamTotal / MAX_BYTE); // 取得流文件需要分开的数量
                    leaveByte = (int) streamTotal % MAX_BYTE; // 分开文件之后,剩余的数量

                    if (streamNum > 0) {
                        for (int j = 0; j < streamNum; ++j) {
                            inOutbyte = new byte[MAX_BYTE];
                            // 读入流,保存在byte数组
                            bInStream.read(inOutbyte, 0, MAX_BYTE);
                            outputstream.write(inOutbyte, 0, MAX_BYTE); // 写出流
                        }
                    }
                    // 写出剩下的流数据
                    inOutbyte = new byte[leaveByte];
                    bInStream.read(inOutbyte, 0, leaveByte);
                    outputstream.write(inOutbyte);
                    outputstream.closeEntry(); // Closes the current ZIP entry
                    // and positions the stream for
                    // writing the next entry
                    bInStream.close(); // 关闭
                    inStream.close();
                }
            }
        } catch (IOException e) {
            throw e;
        }
    }

    public static ResponseEntity<byte[]> downloadZip(File file, String stuId) throws Exception {

        String path = FileUploadUtil.PATH + file.getName();
        File downFile = new File(path);
        HttpHeaders headers = new HttpHeaders();
        String fileName = new String((stuId + ".zip").getBytes("UTF-8"), "iso-8859-1");
        headers.setContentDispositionFormData("attachment", fileName);
        headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
        ResponseEntity<byte[]> fileData = new ResponseEntity<byte[]>(FileUtils.readFileToByteArray(downFile), headers, HttpStatus.CREATED);
        file.delete();
        return fileData;
    }
}
